package com.vegetable.modules.service.baseData.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vegetable.common.utils.R;
import com.vegetable.modules.entity.baseData.CategoryDO;
import com.vegetable.modules.form.CategoryQuery;
import com.vegetable.modules.mapper.baseData.CategoryMapper;
import com.vegetable.modules.service.baseData.ICategoryService;
import com.vegetable.modules.vo.CategoryDTO;
import com.vegetable.modules.vo.category.CategoryTreeDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 分类信息业务逻辑实现类
 * </p>
 * @author Administrator
 */
@Slf4j
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, CategoryDO> implements ICategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 新增分类
     *
     * @param categoryDO 分类信息
     * @return 操作结果
     */
    @Override
    @Transactional
    public boolean addCategory(CategoryDO categoryDO) {
        if (categoryDO.getCategoryName() == null || categoryDO.getCategoryName().isEmpty()) {
            throw new IllegalArgumentException("分类名称不能为空");
        }

        if (categoryMapper.findByCategoryName(categoryDO.getCategoryName()) != null) {
            throw new IllegalArgumentException("分类名称已存在");
        }

        return save(categoryDO);
    }

    /**
     * 删除分类
     *
     * @param id 分类ID
     * @return 操作结果
     */
    @Override
    @Transactional
    public int deleteCategory(Long id) {
        CategoryDO category = getById(id);
        if (category == null) {
            throw new RuntimeException("分类信息不存在");
        }
        if (!categoryMapper.findByParentId(id).isEmpty()) {
            throw new RuntimeException("存在子分类，无法删除");
        }
        return categoryMapper.deleteById(id);
    }

    /**
     * 修改分类
     *
     * @param categoryDO 分类信息
     * @return 操作结果
     */
    @Override
    @Transactional
    public boolean updateCategory(CategoryDO categoryDO) {
        if (getById(categoryDO.getId()) == null) {
            throw new IllegalArgumentException("分类信息不存在");
        }
        return updateById(categoryDO);
    }

    /**
     * 查询分类列表
     * @param query 查询条件
     * @return 分类列表
     */
    @Override
    public List<CategoryDTO> getCategoryList(CategoryQuery query) {
        // 根据条件筛选分类数据
        // 这里简化为直接查询全部，实际应用中需要根据query条件构造查询
        List<CategoryDO> categoryDOList = baseMapper.selectList(new QueryWrapper<>());
        return categoryDOList.stream().map(categoryDO -> {
            CategoryDTO categoryDTO = new CategoryDTO();
            BeanUtils.copyProperties(categoryDO, categoryDTO);
            return categoryDTO;
        }).collect(Collectors.toList());
    }

    /**
     * 查询单个分类详情
     * @param id 分类ID
     * @return 分类详情
     */
    @Override
    public CategoryDTO getCategoryById(Long id) {
        CategoryDO category = getById(id);
        if (category == null) {
            throw new IllegalArgumentException("分类信息不存在");
        }

        CategoryDTO categoryDTO = new CategoryDTO();
        BeanUtils.copyProperties(category, categoryDTO);
        return categoryDTO;
    }

    @Override
    public List<CategoryTreeDTO> getCategoryTree() {
        QueryWrapper<CategoryDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", 0).orderByAsc("sort_order");
        List<CategoryDO> rootCategories = list(queryWrapper);

        List<CategoryTreeDTO> categoryDTOTrees = new ArrayList<>();
        for (CategoryDO rootCategory : rootCategories) {
            CategoryTreeDTO rootDTO = convertDOToTreeDTO(rootCategory);
            rootDTO.setChildren(getChildrenTree(rootCategory.getId()));
            categoryDTOTrees.add(rootDTO);
        }

        return categoryDTOTrees;
    }

    @Override
    public R updateCategorySortOrder(Long id, Integer sortOrder) {
        CategoryDO categoryDO = getById(id);
        if (categoryDO == null) {
            return  R.fail( "分类信息不存在");
        }

        categoryDO.setSortOrder(sortOrder);
        categoryDO.setUpdateBy("admin"); // 这里假设是admin操作
        categoryDO.setUpdateTime(new Date());
        updateById(categoryDO);

        return R.data(categoryDO);
    }

    private boolean isValidParentId(Long parentId) {
        if (parentId == 0) {
            return true;
        }
        return getById(parentId) != null;
    }

    private CategoryDO convertDTOToDO(com.vegetable.modules.vo.category.CategoryDTO categoryDTO) {
        CategoryDO categoryDO = new CategoryDO();
        categoryDO.setCategoryName(categoryDTO.getCategoryName());
        categoryDO.setParentId(categoryDTO.getParentId());
        categoryDO.setSortOrder(categoryDTO.getSortOrder());
        categoryDO.setCategoryType(categoryDTO.getCategoryType());
        categoryDO.setStorageTips(categoryDTO.getStorageTips());
        categoryDO.setCreateBy("admin"); // 这里假设是admin操作
        categoryDO.setCreateTime(new Date());
        categoryDO.setUpdateBy("admin"); // 这里假设是admin操作
        categoryDO.setUpdateTime(new Date());
        return categoryDO;
    }

    private com.vegetable.modules.vo.category.CategoryDTO convertDOToDTO(CategoryDO categoryDO) {
        com.vegetable.modules.vo.category.CategoryDTO categoryDTO = new com.vegetable.modules.vo.category.CategoryDTO();
        categoryDTO.setId(categoryDO.getId());
        categoryDTO.setCategoryName(categoryDO.getCategoryName());
        categoryDTO.setParentId(categoryDO.getParentId());
        categoryDTO.setSortOrder(categoryDO.getSortOrder());
        categoryDTO.setCategoryType(categoryDO.getCategoryType());
        categoryDTO.setStorageTips(categoryDO.getStorageTips());
        categoryDTO.setCreateBy(categoryDO.getCreateBy());
        categoryDTO.setUpdateBy(categoryDO.getUpdateBy());
        return categoryDTO;
    }

    private CategoryTreeDTO convertDOToTreeDTO(CategoryDO categoryDO) {
        CategoryTreeDTO categoryDTO = new CategoryTreeDTO();
        categoryDTO.setId(categoryDO.getId());
        categoryDTO.setCategoryName(categoryDO.getCategoryName());
        categoryDTO.setParentId(categoryDO.getParentId());
        categoryDTO.setSortOrder(categoryDO.getSortOrder());
        categoryDTO.setCategoryType(categoryDO.getCategoryType());
        categoryDTO.setStorageTips(categoryDO.getStorageTips());
        categoryDTO.setCreateBy(categoryDO.getCreateBy());
        categoryDTO.setUpdateBy(categoryDO.getUpdateBy());
        return categoryDTO;
    }

    private List<CategoryTreeDTO> getChildrenTree(Long parentId) {
        QueryWrapper<CategoryDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", parentId).orderByAsc("sort_order");
        List<CategoryDO> childCategories = list(queryWrapper);

        List<CategoryTreeDTO> categoryDTOTrees = new ArrayList<>();
        for (CategoryDO childCategory : childCategories) {
            CategoryTreeDTO childDTO = convertDOToTreeDTO(childCategory);
            childDTO.setChildren(getChildrenTree(childCategory.getId()));
            categoryDTOTrees.add(childDTO);
        }

        return categoryDTOTrees;
    }
}